﻿using System;
using System.Windows;
using System.IO;

using PasswordProvider.ViewModel.Properties;
using ModelSettings = PasswordProvider.ObjectModel.Properties.Settings;
using PasswordProvider.ObjectModel;
using PasswordProvider.ViewModel.Framework;
using PasswordProvider.ViewModel.Service;

namespace PasswordProvider.ViewModel
{
    public class WelcomeViewModel : VisualViewModel
    {
        internal WelcomeViewModel()
        {
            UseDefaultLocation.IsChecked = true;
            // If the active file path is not set yet, this is the first run.
            if (String.IsNullOrEmpty(ModelSettings.Default.ActiveFilePath))
            {
                _heading = Strings.Welcome_WelcomeMessage;
            }
            else
            {
                // The active file has been set but it is missing.
                _heading = Strings.Welcome_MissingFileMessage;                
            }

            // Check for existing file at the backup location.
            if (!String.IsNullOrEmpty(ModelSettings.Default.BackupFilePath) &&
                     File.Exists(ModelSettings.Default.BackupFilePath))
            {
                RestoreFromBackup.Visibility = Visibility.Visible;
                RestoreFromBackup.IsChecked = true;
            }
            else
            {
                RestoreFromBackup.Visibility = Visibility.Collapsed;
            }

            // Check for file at the default location.
            if (File.Exists(DefaultFilePath))
            {
                OpenDefaultLocation.Visibility = Visibility.Visible;
                OpenDefaultLocation.IsChecked = true;
            }
            else
            {
                OpenDefaultLocation.Visibility = Visibility.Collapsed;
            }

        }

        #region Public Properties

        public string Heading
        {
            get { return _heading; }            
        } private string _heading;

        /// <summary>
        /// Create a new file at the default location
        /// </summary>
        public ToggleViewModel UseDefaultLocation
        {
            get
            {
                if (_useDefaultLocation == null)
                {
                    _useDefaultLocation = new ToggleViewModel(
                        Strings.Welcome_UseDefault_DisplayName,
                        Strings.Welcome_UseDefault_ToolTip);

                    _useDefaultLocation.IsCheckedChanged +=
                        (isChecked) =>
                        {
                            if (isChecked)
                            {
                                FilePath.Text = DefaultFilePath;                             
                            }
                        };
                }
                return _useDefaultLocation;
            }
        } private ToggleViewModel _useDefaultLocation;
        /// <summary>
        /// Create a new file at a location of choice.
        /// </summary>
        public ToggleViewModel ChooseOwnLocation
        {
            get
            {
                if (_chooseOwnLocation == null)
                {
                    _chooseOwnLocation = new ToggleViewModel(
                        Strings.Welcome_SelfSelect_DisplayName,
                        Strings.Welcome_SelfSelect_ToolTip);

                    _chooseOwnLocation.IsCheckedChanged +=
                        (isChecked) =>
                        {
                            if (isChecked)
                            {
                                FilePath.Text = String.Empty;
                            }
                        };
                }
                return _chooseOwnLocation;
            }
        } private ToggleViewModel _chooseOwnLocation;
        /// <summary>
        /// Open an existing file
        /// </summary>
        public ToggleViewModel OpenExistingFile
        {
            get
            {
                if (_openExistingFile == null)
                {
                    _openExistingFile = new ToggleViewModel(
                        Strings.Welcome_OpenExisting_DisplayName,
                        Strings.Welcome_OpenExisting_ToolTip);

                    _openExistingFile.IsCheckedChanged +=
                        (isChecked) =>
                        {
                            if (isChecked)
                            {
                                FilePath.Text = null;
                            }
                        };
                    
                }
                return _openExistingFile;
            }
        } private ToggleViewModel _openExistingFile;
        /// <summary>
        /// Restore the backup file
        /// </summary>
        public ToggleViewModel RestoreFromBackup
        {
            get
            {
                if (_restoreFromBackup == null)
                {
                    _restoreFromBackup = new ToggleViewModel(
                        Strings.Welcome_RestoreBackup_DisplayName,
                        Strings.Welcome_RestoreBackup_ToolTip);

                    _restoreFromBackup.IsCheckedChanged +=
                        (isChecked) =>
                        {
                            if (isChecked)
                            {
                                FilePath.Text = ModelSettings.Default.BackupFilePath;
                            }
                        };
                }
                return _restoreFromBackup;
            }
        } private ToggleViewModel _restoreFromBackup;
        /// <summary>
        /// Open file that exists at the default location
        /// </summary>
        public ToggleViewModel OpenDefaultLocation
        {
            get
            {
                if (_openDefaultLocation == null)
                {
                    _openDefaultLocation = new ToggleViewModel(
                        Strings.Welcome_OpenDefault_DisplayName,
                        Strings.Welcome_OpenDefault_ToolTip);

                    _openDefaultLocation.IsCheckedChanged +=
                        (isChecked) =>
                        {
                            if (isChecked)
                            {
                                FilePath.Text = DefaultFilePath;
                            }
                        };

                }
                return _openDefaultLocation;
            }
        } private ToggleViewModel _openDefaultLocation;

        /// <summary>
        /// The file path.
        /// </summary>
        public TextEditViewModel FilePath
        {
            get
            {
                if (_filePath == null)
                {
                    _filePath = new TextEditViewModel(Strings.Welcome_FileLocation_DisplayName, null, null, true);
                }
                return _filePath;
            }
        } private TextEditViewModel _filePath;

        /// <summary>
        /// Browse for file
        /// </summary>
        public CommandViewModel BrowseCommand
        {
            get
            {
                if (_browseCommand == null)
                {
                    _browseCommand = new CommandViewModel(
                        Strings.General_Browse_DisplayString,
                        new RelayCommand(
                            param => BrowseCommandExecuted(), 
                            param => BrowseCommandCanExecute()));
                }
                return _browseCommand;
            }
        }  private CommandViewModel _browseCommand;

        /// <summary>
        /// Ok Command
        /// </summary>
        public CommandViewModel OkCommand
        {
            get
            {
                if (_okCommand == null)
                {
                    _okCommand = new CommandViewModel(
                        Strings.General_Ok,
                        new RelayCommand(
                            param => OkCommandExecuted(), 
                            param => OkCommandCanExecute()));
                }
                return _okCommand;
            }
        } private CommandViewModel _okCommand;

        /// <summary>
        /// Show Help Command
        /// </summary>
        public CommandViewModel ShowHelpCommand
        {
            get
            {
                if (_showHelpCommand == null)
                {
                    _showHelpCommand = new CommandViewModel(
                        Strings.Welcome_ShowHelp_DisplayName,
                        Strings.Welcome_ShowHelp_ToolTip,
                        new RelayCommand(param => ShowHelpCommandExecuted()));
                }
                return _showHelpCommand;
            }
        } private CommandViewModel _showHelpCommand;

        #endregion

        #region Command Handlers

        private bool BrowseCommandCanExecute()
        {
            return (OpenExistingFile.IsChecked || ChooseOwnLocation.IsChecked);
        }

        private void BrowseCommandExecuted()
        {
            if (OpenExistingFile.IsChecked)
            {
                string path = DialogViewService.ShowOpenFileDialog(Strings.Welcome_OpenExisting_DisplayName, null);
                if(path != null)
                    FilePath.Text = path;
            }
            else if (ChooseOwnLocation.IsChecked)
            {
                string path = DialogViewService.ShowSaveFileDialog(Strings.Welcome_SelfSelect_DisplayName, null);
                if (path != null)
                    FilePath.Text = path;
            }
            else throw new InvalidOperationException();
        }
        
        private bool OkCommandCanExecute()
        {
            if (UseDefaultLocation.IsChecked || OpenDefaultLocation.IsChecked || RestoreFromBackup.IsChecked)
                return true;

            if (OpenExistingFile.IsChecked)
                return !String.IsNullOrEmpty(FilePath.Text) && File.Exists(FilePath.Text);

            if (ChooseOwnLocation.IsChecked)
                return !String.IsNullOrEmpty(FilePath.Text);

            throw new InvalidOperationException("Should not have reached here");
        }

        private void OkCommandExecuted()
        {
            // Are we openning an existing file?
            if (OpenExistingFile.IsChecked || OpenDefaultLocation.IsChecked)
            {
                NavigationManager.GoToEnterPasswordView(FilePath.Text);
            }
            // Restoring from backup?
            else if (RestoreFromBackup.IsChecked)
            {
                string currentActivePath = ModelSettings.Default.ActiveFilePath;
                
                NavigationManager.GoToEnterPasswordView(ModelSettings.Default.BackupFilePath);
                
            }
            // Or creating a new file?
            else
            {
                NavigationManager.GoToSetPasswordView(FilePath.Text);
            }

        }

        private void ShowHelpCommandExecuted()
        {
            MessagingService.RequestShowHelp(this, null);
        }

        #endregion

        #region Private Helpers

        /// <summary>
        /// Resolve the default file path from settings value.
        /// </summary>
        private static string DefaultFilePath
        {
            get
            {
                return Environment.ExpandEnvironmentVariables(ModelSettings.Default.DefaultActiveFilePath);
            }
        }

        #endregion

    }
}
